package com.example.jdbcdemo.controller;

import com.example.jdbcdemo.mapper.*;
import com.example.jdbcdemo.pojo.Goods;
import com.example.jdbcdemo.pojo.Order;
import com.example.jdbcdemo.pojo.Product;
import com.example.jdbcdemo.pojo.Storage;
import com.example.jdbcdemo.service.OrderServiceInterface;
import com.example.jdbcdemo.utils.JsonUtil;
import com.example.jdbcdemo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    OrderServiceInterface orderServiceInterface;
    @Autowired
    GroupIdMapMapper groupIdMapMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    StorageMapper storageMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    UserMapper userMapper;

    //进货
    @PostMapping("/addinputorder")
    public JsonUtil addInputOrder(HttpServletRequest request, @RequestBody Map<String,Object> map){
        //操作员id从token获取
        //token中包含了用户名，根据用户名获取用户id
        String token= (String) request.getHeader("token");
        String spiltss[]=token.split("#");
        String userName=spiltss[0];
        int userId=userMapper.queryUserByname(userName).getId();
        //新增权限判断，只有老板和进货调货员（对应usertype为0和1）能够进货
        int userType=userMapper.queryUserByname(userName).getUserType();
        if (userType!=0&&userType!=1)
        {
            return new JsonUtil(1000,"权限不足",null);
        }

        int storageId= (int) map.get("storageId");//仓库id
        int productId= (int) map.get("productId");//涉及的商品id
        int num= (int) map.get("num");//商品数量
        if (num<=0)
        {
            return new JsonUtil(501,"数量小于0","");
        }
        Storage storage= storageMapper.queryStorageById(storageId);
        if (storage==null)
        {
            return new JsonUtil(500,"仓库不存在","");
        }
        Product product= productMapper.queryProductById(productId);
        if (product==null)
        {
            return new JsonUtil(500,"需要先创建商品","");
        }
        //若是没有对应的库存的话就创建一个库存数为0的新库存
        if (goodsMapper.queryGoodsByTwo(productId,storageId)==null)
        {
            goodsMapper.addGoods(new Goods(0,productId,storageId,0));
        }
        double price=Double.parseDouble(map.get("price").toString());//进货价
        int groupId= groupIdMapMapper.queryGroupIdMapMaxId()+1;//获取当前最大的groupid再加1
        Order order=new Order(0,userId,0,storageId,productId,num,price,groupId);
        return orderServiceInterface.addOrderj(order);
    }



}
